// 错题本API
import { NextRequest } from 'next/server';
import { MistakeDB } from '@/lib/mysql';
import { getCurrentUser, ApiResponse } from '@/lib/auth';

// 获取用户错题列表
export async function GET(request: NextRequest) {
  try {
    // 验证用户登录
    const currentUser = getCurrentUser();
    if (!currentUser) {
      return ApiResponse.unauthorized('请先登录');
    }

    // 获取查询参数
    const { searchParams } = new URL(request.url);
    const reviewedParam = searchParams.get('reviewed');
    
    let reviewed: boolean | undefined;
    if (reviewedParam === 'true') {
      reviewed = true;
    } else if (reviewedParam === 'false') {
      reviewed = false;
    }

    // 获取错题列表
    const mistakes = await MistakeDB.getUserMistakes(currentUser.userId, reviewed);

    return ApiResponse.success({
      mistakes,
      total: mistakes.length,
    });
  } catch (error) {
    console.error('获取错题列表错误:', error);
    return ApiResponse.serverError('获取错题列表失败');
  }
}

// 添加错题（通常由submit API自动调用，这里提供手动添加接口）
export async function POST(request: NextRequest) {
  try {
    // 验证用户登录
    const currentUser = getCurrentUser();
    if (!currentUser) {
      return ApiResponse.unauthorized('请先登录');
    }

    // 解析请求体
    const body = await request.json();
    const {
      topicId,
      topicName,
      questionIndex,
      questionStem,
      correctAnswer,
      userAnswer,
      solution,
      difficulty,
    } = body;

    // 验证必填字段
    if (
      !topicId ||
      !topicName ||
      questionIndex === undefined ||
      !questionStem ||
      !correctAnswer
    ) {
      return ApiResponse.error('缺少必填字段');
    }

    // 添加错题
    await MistakeDB.add(
      currentUser.userId,
      topicId,
      topicName,
      questionIndex,
      questionStem,
      correctAnswer,
      userAnswer || '',
      solution || '',
      difficulty || 1
    );

    return ApiResponse.success(null, '错题添加成功');
  } catch (error) {
    console.error('添加错题错误:', error);
    return ApiResponse.serverError('添加错题失败');
  }
}
